package com.udaos.modules.physical.controllers;

import java.io.OutputStream;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import com.udaos.common.base.AppException;
import com.udaos.common.base.Result;
import com.udaos.common.page.DataTableColumn;
import com.udaos.common.page.DataTableOrder;
import com.udaos.common.util.DateUtil;
import com.udaos.common.util.StringUtil;
import com.udaos.models.field.Ud_temp_field;
import com.udaos.models.physical.Ud_physical_code;
import com.udaos.models.physical.Ud_physical_code_batch;
import com.udaos.modules.customer.services.UdCustomerService;
import com.udaos.modules.physical.services.UdPhysicalCodeBatchService;
import com.udaos.modules.physical.services.UdPhysicalCodeService;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

/**
 * 体检码
 * 
 * @author mutaotao
 *
 */
@IocBean
@At("/platform/physical")
public class UdPhysicalCodeController {

	@Inject
	private UdPhysicalCodeService codeService;

	@Inject
	private UdCustomerService customerService;
	
	@Inject
	private UdPhysicalCodeBatchService batchService;

	/**
	 * 首页
	 */
	@At("")
	@Ok("beetl:/platform/physical/index.html")
	@RequiresAuthentication
	public void index() {

	}

	/**
	 * 加載數據列表
	 * 
	 * @param mobile
	 * @param name
	 * @param length
	 * @param start
	 * @param draw
	 * @param order
	 * @param columns
	 * @return
	 */
	@At
	@Ok("json:full")
	@RequiresAuthentication
	public Object data(@Param("batch_no") String batch_no, @Param("length") int length, @Param("start") int start, @Param("draw") int draw,
			@Param("::order") List<DataTableOrder> order, @Param("::columns") List<DataTableColumn> columns) {
		
		Cnd cnd = Cnd.NEW();
		if(!Strings.isBlank(batch_no)){
			//获取批次
			Ud_physical_code_batch batch=batchService.fetch(Cnd.where("batch_no", "=", batch_no));
			if(null != batch){
				cnd.and("batch_id", "=", batch.getId());
			}else{
				//无效的批次号
				cnd.and("batch_id", "=", "aaaaaaaaa");
			}
		}
		cnd.asc("sn");
		return codeService.data(length, start, draw, order, columns, cnd, null);
	}

	/**
	 * 新增体检码
	 * 
	 * @return
	 */
	@At
	@Ok("beetl:/platform/physical/add.html")
	@RequiresAuthentication
	public void add() {

	}

	/**
	 * 新增体检码
	 * 
	 * @param code
	 * @param req
	 * @return
	 */
	@At
	@Ok("json")
	@RequiresAuthentication
	public Object addDo(Integer count, String batch_no) {
		try {
			codeService.createCode(count, batch_no);
		} catch (AppException e) {
			return Result.error(e.getMessage());
		}
		return Result.success("system.success");
	}

	@At
	@Ok("json")
	public String getCustomer(String customerid) {
		if (StringUtil.isNullOrEmpty(customerid)) {
			return "";
		} else {
			return customerService.fetch(customerid).getMobile();
		}
	}
	@At
	@Ok("json")
	public String getBatchNo(String batchId) {
		if (StringUtil.isNullOrEmpty(batchId)) {
			return "";
		} else {
			return batchService.fetch(batchId).getBatch_no();
		}
	}
	
	
	/**
	 * 导出
	 * @param lnglat
	 * @param ll
	 * @param name
	 * @return
	 */
	@At
	@RequiresAuthentication
	public void export(@Param("batch_no") String batch_no,HttpServletRequest request,HttpServletResponse response){
		//获取数据
		Result result=new Result();
		Cnd cnd = Cnd.NEW();
		if (!Strings.isBlank(batch_no)){
			//获取批次
			Ud_physical_code_batch batch=batchService.fetch(Cnd.where("batch_no", "=", batch_no));
			if(null != batch){
				cnd.and("batch_id", "=", batch.getId());
			}else{
				//无效的批次号
				cnd.and("batch_id", "=", "aaaaaaaaa");
			}
		}
		cnd.asc("sn");
		List<Ud_physical_code> list=codeService.query(cnd);
		try{
			  Long now=System.currentTimeMillis(); 
		      String fname =now.toString();// DateUtil.format(new Date(), "yyyy-MM-dd");//Excel文件名
		      OutputStream os = response.getOutputStream();//取得输出流
		      response.reset();//清空输出流
		      response.setHeader("Content-disposition", "attachment; filename=" + fname + ".xls");//设定输出文件头
		      response.setContentType("application/msexcel");//定义输出类型
		      WritableWorkbook wbook = Workbook.createWorkbook(os); //建立excel文件
		      WritableSheet wsheet = wbook.createSheet("优道学车体检码", 0); //sheet名称
		      //设置excel标题
		      WritableFont wfont = new WritableFont(
		          WritableFont.ARIAL, 20,
		          WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,
		          Colour.BLACK);
		      WritableCellFormat wcfFC = new WritableCellFormat(wfont);
		      wcfFC.setAlignment(Alignment.CENTRE);//水平居中对齐
		      //竖直方向居中对齐
		      wcfFC.setVerticalAlignment(VerticalAlignment.CENTRE);
		      if(null == list || list.size()==0){
		    	  Label wlabel= new Label(0, 0, "暂无数据", wcfFC);//创建单元格设置样式
		    	  wsheet.addCell(wlabel);
		    	  wbook.write(); //写入文件
			      wbook.close();
			      os.close();
			      
			      return;
		      }
		      Label wlabel1= new Label(0, 0, "优道学车体检码", wcfFC);//创建单元格设置样式
		      //合并单元格，参数依次为：列索引、行索引、列索引+需要合并的列的个数、行索引+需要合并的行的个数
		      wsheet.mergeCells(0, 0, 1, 0);
		      //将单元格添加到工作表wsheet相应的单元格中
		      wsheet.addCell(wlabel1);
		      wfont = new WritableFont(
			          WritableFont.ARIAL, 14,
			          WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,
			          Colour.BLACK);
		      WritableCellFormat wcfFC1 = new WritableCellFormat( wfont);
		      //设置单元格宽度，以字符为单位
	          wsheet.setColumnView(0, 40);
	          wsheet.setColumnView(1, 30);
	          wcfFC1.setAlignment(Alignment.CENTRE);//水平居中对齐
	          wcfFC1.setBorder(Border.ALL,BorderLineStyle.THIN); //设置边框
		      wcfFC1.setBackground(Colour.GRAY_25); //设置背景色
		      wsheet.addCell(new Label(0, 1, "序号", wcfFC1));//创建单元格设置样式);
		      wsheet.addCell(new Label(1, 1, "验证码", wcfFC1));;
		      int i=2;
		      
		      WritableFont wfont1 = new WritableFont(
			          WritableFont.createFont("宋体"), 14,WritableFont.NO_BOLD
			          , false, UnderlineStyle.NO_UNDERLINE,Colour.BLACK);
		      WritableCellFormat wcfFC2 = new WritableCellFormat( wfont1);
		      wcfFC2.setAlignment(Alignment.CENTRE);//水平居中对齐
		      wcfFC2.setBorder(Border.ALL,BorderLineStyle.THIN); //设置边框
		     
		      for (int j = 0; j < list.size(); j++) {
		    	  Ud_physical_code u=list.get(j);
		    	  wsheet.addCell(new Label(0, i, String.valueOf(u.getSn()), wcfFC2));
			      wsheet.addCell(new Label(1, i, String.valueOf(u.getCode()), wcfFC2));
			      i++;
		      }
		      i=2;
		      wbook.write(); //写入文件
		      wbook.close();
		      os.close();
		    }catch(Exception e){
			    return ;
		    }
		
	    return;
		
	}
	
	@At
	@Ok("json")
	public Object test(){
		String code=codeService.getCode();
		return code;
	}

}
